<template>
  <div class="upload-photo">
    <div class="block">
      <img
        :src="previewImg"
        ref="image"
        style="width: 100%; height: 50%"
        alt=""
      />
    </div>
    <van-nav-bar
      class="tool-bar"
      left-text="取消"
      right-text="确定"
      @click-left="cancel"
      @click-right="confirm"
    />
  </div>
</template>

<script>
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.css";
import { changeUserPhoto } from "@/api/user";
export default {
  name: "Updatephoto",
  props: {
    file: {
      require: true,
    },
  },
  data() {
    return {
      cropper: null,
    };
  },
  computed: {
    previewImg () {
      return this.file && window.URL.createObjectURL(this.file)
    }
  },
  mounted() {
      this.$nextTick(() => {
        const image = this.$refs.image
        this.cropper = new Cropper(image, {
            viewMode: 1,
            dragMode: "move",
            movable:true,
            aspectRatio: 1,
            cropBoxResizable: false,
            zoomOnTouch: true,
            background: false,
            preview: ".small",
        })
      })
      
  },
  methods: {
    confirm() {
      console.log("confirm");
      this.cropper.getCroppedCanvas().toBlob( async blob => {
        console.log(blob)
        if (blob.size > 1024 * 50) {
          this.$toast.fail('上传文件不能大于50M')
          return
        }
        const fd = new FormData()
        fd.append('photo',blob)
        const res = await changeUserPhoto(fd)
        if (res.status === 200) {
          this.$toast.success('头像上传成功')
          this.$emit('close')
        }
      })
    },
    cancel () {
        this.$emit('close')
    }
  },
};
</script>

<style lang="less" scoped>
.upload-photo {
  height: 100%;
  .tool-bar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
  }
  /deep/.cropper-view-box{
    border-radius: 50%;
  }
}
</style>